$(document).ready(function() {
    
//    AJAX PAGING
    var count = 1;
    var isLoaded = false;
    $(".paging").hide();
    
    $(window).scroll(function(){
        var position = ($(document).height() - $(window).height());    
        //If scrollbar is at the bottom 
        if  ($(window).scrollTop() == position) {      
            
            if (count < pages && !isLoaded) {
                $("#content").append("<div style='text-align:center'><img src='./img/ajax-loader.gif' alt='loading ... ' id='busy-indicator' /></div>");
                var timer = 2;
                isLoaded = true;
                count++; //increase the ajax counter
                
            }
            $("#content").append("<div class='batch' style='display:none;'></div>"); //append a container to hold ajax content
            var url = $("a#next").attr("href"); //extract the URL from the "next" link
            $(".paging").remove(); // remove the old pagination links because new ones will be loaded via ajax
            $("div.batch").load(url, function(response, status, xhr) {
                if (status == "error") {
                  var msg = "Sorry but there was an error: ";
                  alert(msg + xhr.status + " " + xhr.statusText);
                } else {
                    $(this).attr("class","loaded"); //change the class name so it will not be confused with the next batch
                    $("#busy-indicator").parent().remove();
                    $(".paging").hide(); //hide the new paging links
                    $(this).fadeIn();
                    isLoaded = false;   
                }
            });
        }
    });

    
    
    function countdown(id) {
        
        var minutes;
        var seconds;
               
        timerId[id] = setInterval(function(){
            
            seconds = time_left[id] % 60;
            minutes = Math.floor(time_left[id]/60);
            
            seconds = add_leading_zero(seconds);
		    minutes = add_leading_zero(minutes);
            
            $("#countdown" + id).html(minutes + ":" + seconds);
            
            if (time_left[id] == 0) {
                clearInterval(timerId[id]);
            } else {
                time_left[id]--;
                // Saving Time left
                $.ajax({
                    type: 'POST',
                    url:  './auctions/updateTimer', 
                    data: "time_left=" + time_left[id] + "&id=" + $("#auction" + id).val(),
                    success: function(data,textStatus, xhr) {
                    },
                    error: function(xhr, textStatus, error) {
                        alert(textStatus);
                    } 
                });
            }
        }, 1000);
        
        function add_leading_zero(n) {
		    if(n.toString().length < 2) {
			    return '0' + n;
		    } else {
			    return n;
		    }
	    }
    }

       // SOLD
//    $(".auction li").find('input[value=Sold]').parents("li").addClass('sold');

    $("#UserUpdateTokenForm").hide();
//    BUY TOKENS
    $("#purchase").click(function(){
        $("#UserUpdateTokenForm").slideToggle('slow');
    });
    // CONFIRMATION
    $("input[value=buy]").click(function(){
        if (!$('#UserToken').val()) {
            alert("Please enter the number of tokens you wanna buy!");
            return false;
        } else
            return confirm("S$" + $('#UserToken').val() + " will be deducted form your account, is it ok?");
    });
    
    
    //while (time_left['bid6'] > 0) {
        //    countdown("bid1");
    if(typeof(initiate) != "undefined" && initiate !== null) {
        $.each(initiate, function(key, val) {
    //        console.log(val);
            countdown("bid" + val);
        });
        //countdown("bid10");
        //countdown("bid0");   
    }

 
    // BIDDING
    $(".bid").click(function(event){
        if (token == "") {
            alert('You have to login to bid');
        } else if (token == 0) {
            alert('You\'re running out of tokens. Please buy more tokens before you can continue to bid!');
        } else if (token > 0 && $("#countdown" + $(this).attr('id')).html() != "00:00") {
//            alert(+($("#price" + $(this).attr('id')).text()));
            price = parseFloat($("#price" + $(this).attr('id')).text()) + 0.5;
            $("#price" + $(this).attr('id')).html(price);
            time_left[$(this).attr('id')] += 20;
            $("#bidder" + $(this).attr('id')).html(user);
            token--;
            // Saving current tokens
            $.ajax({
                type: 'POST',
                url:  './users/updateToken', 
                data: "token=" + token,
                success: function(data,textStatus, xhr) {
//                    alert(data);
                },
                error: function(xhr, textStatus, error) {
                    alert(textStatus);
                } 
            });
            // Saving current bid (bidder + price)
            $.ajax({
                type: 'POST',
                url:  './auctions/updateBid', 
                data: "bid=" + price + "&id=" + $("#auction" + $(this).attr('id')).val() + "&bidder=" + $("#bidder" + $(this).attr('id')).html(),
                success: function(data,textStatus, xhr) {
                },
                error: function(xhr, textStatus, error) {
                    alert(textStatus);
                } 
            });
        }
        
    });

    
});
